import { Service } from 'egg';
import { Category } from './category';

interface ProductionRequestType {
  name: string
  description: string
  count: number
  price: number
  categoryId: number
  pid: string
}

interface ProductionType {
  id: number
  name: string
  description: string
  createAt: string
  updateAt: string
  pid: string
  categoryId: number
  sold: number
  price: number
  count: number
}
export default class GoodService extends Service {

  public async create(options: ProductionRequestType) {
    const { app, ctx } = this;
    await app.mysql.insert('goods', {
      ...options,
      createAt: ctx.helper.getCreateAt(),
      updateAt: ctx.helper.getCreateAt(),
    });
    const goods = await app.mysql.select('goods', { where: { pid: options.pid } });
    const good = goods[0] as ProductionType;
    return good;
  }

  public async update(goodId, options) {
    const { app } = this;
    const goods = await app.mysql.select('goods', { where: { id: goodId } });
    if (goods.length === 0) return { status: 400, err: '商品不存在！' };
    await app.mysql.update('goods', {
      id: goodId,
      ...options,
    });
    return { message: '商品更新成功！' };
  }

  /**
   * 获取商品列表
   * @param where   查询条件
   * @param limit   查询的个数
   * @param page    查询页数
   */
  public async getGoods(where: any = {}, limit = 10, page = 1, orders: [string, 'desc' | 'asc' | 'DESC' | 'ASC'][] = []) {
    const { app } = this;
    const offset = limit * (page - 1);

    const options: { [key: string]: any } = { limit, offset };
    if (Object.keys(where).length !== 0) options.where = where;
    if (orders.length !== 0) options.orders = orders;

    const res = await app.mysql.select('goods', options) as ProductionType[];
    const categories = await app.mysql.select('categories');
    const data = res.map(item => ({
      id: item.id,
      pid: item.pid,
      price: item.price,
      count: item.count,
      createAt: item.createAt,
      updateAt: item.updateAt,
      name: item.name,
      description: item.description,
      sold: item.sold,
      category: (categories as Category[]).find(category => category.id === item.categoryId) as Category,
    }));
    return data;
  }

  public async searchGoods(search: { [key: string]: string } = {}, orders: [string, 'desc' | 'asc' | 'DESC' | 'ASC'][] = [], limit = 10, offset = 1) {
    const { app } = this;
    let sql = 'select * from goods';
    const searchOption: string[] = [];
    for (const key in search) {
      if (Object.prototype.hasOwnProperty.call(search, key)) {
        const value = search[key];
        if (key === 'price') {
          searchOption.push(`${key} >= ${value[0]} and ${key} < ${value[1]}`);
        } else {
          if (Array.isArray(value)) {
            const valueArray = value.map(item => `${key} like \'%${item}%\'`);
            searchOption.push(valueArray.join(' or '));
          } else {
            searchOption.push(`${key} like \'%${value}%\'`);
          }
        }
      }
    }
    if (searchOption.length !== 0) sql += ` where ${searchOption.join(' and ')}`;

    const ordersOptions: string[] = [];
    orders.forEach(order => {
      ordersOptions.push(order.join(' '));
    });
    if (ordersOptions.length !== 0) sql += ` order by ${ordersOptions.join(',')}`;
    sql += ` limit ${offset},${limit}`;

    const res = await app.mysql.query(sql) as ProductionType[];
    const categories = await app.mysql.select('categories');
    const data = res.map(item => ({
      id: item.id,
      pid: item.pid,
      price: item.price,
      count: item.count,
      createAt: item.createAt,
      updateAt: item.updateAt,
      name: item.name,
      description: item.description,
      sold: item.sold,
      category: (categories as Category[]).find(category => category.id === item.categoryId) as Category,
    }));
    return data;
  }

  public async findGoodById(id: string) {
    const { app } = this;
    const goods = await app.mysql.select('goods', { where: { id } });
    if (goods.length === 0) return { status: 400, err: '商品不存在！' };
    const good = goods[0] as ProductionType;
    const categories = await app.mysql.select('categories');
    return {
      id: good.id,
      name: good.name,
      description: good.description,
      price: good.price,
      count: good.count,
      sold: good.sold,
      pid: good.pid,
      category: (categories as Category[]).find(category => category.id === good.categoryId) as Category,
      createAt: good.createAt,
      updateAt: good.updateAt,
    };
  }

  public async removeGood(goodId) {
    const { app } = this;
    const goods = await app.mysql.select('goods', { where: { id: goodId } });
    if (goods.length === 0) return { status: 400, err: '该商品不存在！' };
    await app.mysql.delete('goods', { id: goodId });
    return { message: '删除成功！' };
  }
}
